#include "../include/dir.h"

int makePath(path_t *path, const char *destDir, char *newVirPath, char *newRealPath){
    //判断绝对 相对路径
    if(destDir[0] == '/'){
        //绝对路径
        sprintf(newVirPath, "%s", destDir);
    }
    else{
        //相对路径
        if(strcmp(path->virtualPath, "/") == 0){
            //在虚拟根目录
            sprintf(newVirPath, "/%s", destDir);
        }
        else{
            sprintf(newVirPath, "%s/%s", path->virtualPath, destDir);
        }
    }

    //规范路径 并执行入栈出栈
    char stack[50][MAX_PATH_LEN] = {0}; //栈存放目录名
    int top = 0;
    char *token;
    char *saveptr; //strtok_r所需的维护指针
    token = strtok_r(newVirPath, "/", &saveptr);
    while(token){
        if(strcmp(token, ".") == 0){} //无视
        else if(strcmp(token, "..") == 0){
            //虚拟根目录则无视
            if(top > 0){
                top--;
            }
        }
        else{
            strncpy(stack[top], token, MAX_PATH_LEN-1);
            top++;
        }
        token = strtok_r(NULL, "/", &saveptr);
    }

    //出栈->拿到规范后的新虚拟路径
    bzero(newVirPath, MAX_PATH_LEN);
    for(int i = 0; i < top; i++){
        int len = MAX_PATH_LEN-strlen(newVirPath)-1;
        strncat(newVirPath, "/", len);
        strncat(newVirPath, stack[i], len);
    }

    //如果destDir是.或.. 被无视 空栈则虚拟还是/
    if(strlen(newVirPath) == 0){
        strncpy(newVirPath, "/", MAX_PATH_LEN);
    }

    //拼接真实
    strncpy(newRealPath, path->initPath, MAX_PATH_LEN);//初始化
    strncat(newRealPath, newVirPath, MAX_PATH_LEN-strlen(newRealPath)-1);
    
    return 0;
}
